package com.fd.framework.autoconfigure;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

/**
 * swagger 自动配置类
 *
 * @author YangXiaoLong
 * @since 1.0.0
 */
@EnableSwagger2
@ConditionalOnProperty(prefix = "fd.swagger", name = "enable", havingValue = "true")
@EnableConfigurationProperties(value = FdSwaggerProperties.class)
public class SwaggerAutoConfiguration {

    @Value(value = "${spring.application.name}")
    private String applicationName;

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(applicationName + "API文档")
                .description("该文档仅内部成员调试使用")
                .version("V1.0.0")
                .build();
    }

    @Bean
    public BeanPostProcessor springFoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            // 在初始化之后对Bean进行处理
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                // 检查Bean是否是WebMvcRequestHandlerProvider或WebFluxRequestHandlerProvider的实例
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    // 对SpringFox的处理器映射进行定制
                    customizeSpringFoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }
            // 定制SpringFox的处理器映射
            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringFoxHandlerMappings(List<T> mappings) {
                // 过滤掉已经具有PatternParser的映射
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                // 清空原始映射列表并添加定制后的映射
                mappings.clear();
                mappings.addAll(copy);
            }

            // 获取处理器映射列表
            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    // 通过反射获取处理器映射列表的字段
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    assert field != null;
                    field.setAccessible(true);
                    // 返回处理器映射列表
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    // 处理异常，抛出IllegalStateException
                    throw new IllegalStateException(e);
                }
            }
        };
    }

}
